#ifndef LIBSERV_LIBRARY_H
#define LIBSERV_LIBSERV_H

#include <string>
#include <iostream>
#include <vector>
#include <atomic>
#include <functional>
#include <libserv/libserv_message.h>
#ifdef _WINDOWS
#include <windows.h>
namespace libserv{
    int default_print_function(void *arg, std::vector<char> message);
    class Serial{
    public:
        Serial();
        explicit Serial(int serial_device,int frequence);
        void BindCall(int (*bind_function)(void*,std::vector<char>));
        void BindPackageCheck(bool (*check_function)(std::vector<char>));
        int BindPort(int serial_device,int frequence );
        void AnsySend(char *buffer,int buffer_size);
        int Run();
        bool Lock();
        void Release();
    private:
        int (*call_function)(void*,std::vector<char>);
        bool (*check_function)(std::vector<char>);
        int max_queue_size=100;
        bool opened;
        HANDLE hCom;
        HANDLE StopEvent;
        HANDLE SendEvent;
        HANDLE ReadEvent;
    };
}
#endif
#ifdef __linux__
namespace libserv {
    class Serial {
    public:
        explicit Serial();

        explicit Serial(std::string serial_device, int frequence, unsigned char head);

        void bind_call(int(*bind_function)(void *arg, std::vector<char> message));

        void bind_package_check(bool (*check_function)(std::vector<char>));

        int bind_port(std::string serial_device, int frequence);

        int set_serial(int fd, int nSpeed, int nBits, char nEvent, int nStop);

        bool ansy_send(char *buffer, int buffer_size);

        virtual void Run();

        bool is_open() const;

        int release();

        void lock();

        ~Serial();


    public:
        bool is_run();

    protected:
        static int tty_num;
        static std::mutex mu_read_write_port;
        static std::vector<libserv::Message *> messages;

//        std::function<bool(std::vector<char>)> check_function;
//        std::function<int(void *, std::vector<char>)> call_function;
        bool (*check_function)(std::vector<char>);

        int (*call_function)(void *arg, std::vector<char> message);

        int max_queue_size = 100;
        int fd{};
        unsigned char head{};
        std::atomic<bool> m_is_run{};
    };
}
#endif
#endif //LIBSERV_LIBRARY_H